package com.piik.mall.order.interceptor;

import com.piik.common.constant.AuthConstant;
import com.piik.common.dto.MemberDTO;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Configuration
public class AuthInterceptor implements HandlerInterceptor {

    public static ThreadLocal threadLocal = new ThreadLocal();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        // 支付宝的回调我们放过
        String requestURI = request.getRequestURI();
        boolean match = new AntPathMatcher().match("/orderPay/**", requestURI);
        if(match){
            return true;
        }
        // 通过HttpSession获取当前登录的用户信息
        HttpSession session = request.getSession();
        Object attribute = session.getAttribute(AuthConstant.AUTH_SESSION_REDIS);
        if(attribute !=null){
          MemberDTO memberDTO=(MemberDTO)attribute;
            threadLocal.set(memberDTO);
            return true;
        }
        session.setAttribute(AuthConstant.AUTH_SESSION_MSG,"请先登录");
        response.sendRedirect("http://auth.piik.com/login.html");
        return false;
    }
}
